package com.streamsets.datacollector.pileline.stage;

import com.streamsets.datacollector.model.etl.FieldTypeConversionJson;
import com.streamsets.datacollector.model.etl.bean.FieldTypeConversionBean;
import com.streamsets.datacollector.restapi.bean.ConfigConfigurationJson;
import com.streamsets.datacollector.restapi.bean.StageConfigurationJson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  初始化 管道 值替换Stage的配置
 *  stage的完整描述示例如：
 [ {
 "fields" : [ "/created_dt" ],
 "targetType" : "DATETIME",
 "treatInputFieldAsDate" : false,
 "dataLocale" : "en,US",
 "scale" : -1,
 "decimalScaleRoundingStrategy" : "ROUND_UNNECESSARY",
 "dateFormat" : "YYYY_MM_DD_HH_MM_SS",
 "zonedDateTimeFormat" : "ISO_ZONED_DATE_TIME",
 "encoding" : "UTF-8"
 }, {
 "fields" : [ "/updated_dt" ],
 "targetType" : "DATETIME",
 "treatInputFieldAsDate" : false,
 "dataLocale" : "en,US",
 "scale" : -1,
 "decimalScaleRoundingStrategy" : "ROUND_UNNECESSARY",
 "dateFormat" : "YYYY_MM_DD_HH_MM_SS",
 "zonedDateTimeFormat" : "ISO_ZONED_DATE_TIME",
 "encoding" : "UTF-8"
 } ]
 *
 * @author wengzhonghui
 * @date 2020/4/2 10:32
 */
public class InitFieldTypeConversionConfig {

    /*
     * stage instanceName名称
     */
    private static final String STAGE_NAME = "g1_04";

    /*
     * 配置实例 名称
     */
    private static final String RENAME_MAPPING_CONFIG_NAME = "fieldTypeConverterConfigs";


    public static boolean init(StageConfigurationJson stage, FieldTypeConversionJson configDto){
        if (STAGE_NAME.equalsIgnoreCase(stage.getInstanceName())){
            if (configDto != null) {
                List<ConfigConfigurationJson> configs = intConfig(stage.getConfiguration(), configDto);
                stage.setConfiguration(configs);
            } else {
                List<ConfigConfigurationJson> configs =
                    stage.getConfiguration().stream().filter(
                        e -> "fieldTypeConverterConfigs".equals(e.getName())|| "wholeTypeConverterConfigs".equals(e.getName())).collect(Collectors
                        .toList());
                stage.getConfiguration().removeAll(configs);
            }
        }
        return true;
    }

    public static List<ConfigConfigurationJson> intConfig(List<ConfigConfigurationJson> oldConfigs, FieldTypeConversionJson configDto){
        List<ConfigConfigurationJson> newConfigs = new ArrayList<>();
        for(ConfigConfigurationJson config :oldConfigs ){
            config = initNameMappingConfigs(config, configDto.getNameMappingColumns());
            newConfigs.add(config);
        }
        return newConfigs;
    }



    /*
     * 把当值为空时，替换为某个值
     * 格式示例如：
     * [ {
          "fields" : [ "/created_dt" ],
          "targetType" : "DATETIME",
          "treatInputFieldAsDate" : false,
          "dataLocale" : "en,US",
          "scale" : -1,
          "decimalScaleRoundingStrategy" : "ROUND_UNNECESSARY",
          "dateFormat" : "YYYY_MM_DD_HH_MM_SS",
          "zonedDateTimeFormat" : "ISO_ZONED_DATE_TIME",
          "encoding" : "UTF-8"
        }, {
          "fields" : [ "/updated_dt" ],
          "targetType" : "DATETIME",
          "treatInputFieldAsDate" : false,
          "dataLocale" : "en,US",
          "scale" : -1,
          "decimalScaleRoundingStrategy" : "ROUND_UNNECESSARY",
          "dateFormat" : "YYYY_MM_DD_HH_MM_SS",
          "zonedDateTimeFormat" : "ISO_ZONED_DATE_TIME",
          "encoding" : "UTF-8"
        } ]
     * @param [config 原来的配置, columnNames:需要映射的列名列表]
     * @return 返回新生成的配置
     */
    private static ConfigConfigurationJson initNameMappingConfigs(ConfigConfigurationJson config, List<FieldTypeConversionBean> nameMappingColumns){
        List configValList = new ArrayList();
        if(nameMappingColumns != null && nameMappingColumns.size() > 0){
            for(FieldTypeConversionBean valConfig : nameMappingColumns){
                if(valConfig == null ||  valConfig.getFields() == null || valConfig.getFields().size() == 0){
                    continue;
                }
                Map data = new HashMap();
                data.put("fields", getFieldsArray(valConfig.getFields()));
                data.put("targetType", valConfig.getTargetType());
                data.put("dateFormat", valConfig.getDateFormat());
                data.put("treatInputFieldAsDate", valConfig.getTreatInputFieldAsDate());
                data.put("dataLocale", valConfig.getDataLocale());
                data.put("scale", valConfig.getScale());
                data.put("decimalScaleRoundingStrategy", valConfig.getDecimalScaleRoundingStrategy());
                data.put("zonedDateTimeFormat", valConfig.getZonedDateTimeFormat());
                data.put("encoding", valConfig.getEncoding());
                configValList.add(data);
            }
        }
        config = new ConfigConfigurationJson(RENAME_MAPPING_CONFIG_NAME  ,configValList);
        return config;
    }


    private static String[] getFieldsArray(List<String> fields){
        List<String> resultList = new ArrayList<>();
        for(String field : fields){
            resultList.add("/" + field);
        }
        String[] strArray = new String[resultList.size()];
        return resultList.toArray(strArray);
    }

}
